// pages/admin/scan/scan.js
const app = getApp()
var host = app.globalData.host;
var utils = require("../../../utils/util.js");
var self = null;

Page({
  data: {
    themeColor: '',
    price: 0
  },
  onLoad: function (options) {
    self = this;
    self.getStyle();

    if (!wx.getStorageSync("shopUser")) {
      app.globalData.shopUser = null;
      wx.reLaunch({
        url: '/pages/admin/login/login'
      })
    } else {
      app.globalData.shopUser = wx.getStorageSync("shopUser");
    }
  },
  getStyle() {
    self.setData({
      themeColor: app.globalData.themeColor
    })
  },
  onPriceChanged(e) {
    self.setData({
      price: e.detail.value
    })
  },
  scan(e) {
    if (!Number(self.data.price)) {
      wx.showModal({
        title: '提示',
        content: '请输入金额',
        showCancel: false
      })
      return;
    }
    wx.scanCode({
      onlyFromCamera: true,
      success: res => {
        console.log("扫码成功");
        console.log(res);
        var authCode = res.result;

        var url = host + '/yq/api/microPay';
        var params = {
          total: utils.accMul(self.data.price, 100),
          authCode: authCode,
          shop: app.globalData.shopUser.shop,
          suid: app.globalData.shopUser.id
        }
        var success = res => {
          console.log(res);
          if (res.info.result_code == "SUCCESS") {
            wx.showModal({
              title: '提示',
              content: '交易成功',
              showCancel: false
            })
          } else if (res.info.err_code == "SYSTEMERROR" || res.info.err_code == "BANKERROR") { // 支付结果未知，等待5秒查询订单状态
            wx.showLoading({
              title: '请稍等…'
            })
            setTimeout(function() {
              var url = host + '/yq/api/query';
              var params = {
                code: res.info.code
              }
              var success = res => {
                wx.hideLoading();
                var query = res.info;
                if (query.trade_state == 'SUCCESS') {
                  wx.showModal({
                    title: '提示',
                    content: '用户支付成功',
                    showCancel: false,
                    success: res => {
                      wx.navigateBack({
                        delta: 1
                      })
                    }
                  })
                } else if (query.trade_state == 'REVOKED' || query.trade_state == 'PAYERROR') {
                  wx.showModal({
                    title: '提示',
                    content: '支付失败',
                    showCancel: false,
                    success: res => {
                      wx.navigateBack({
                        delta: 1
                      })
                    }
                  })
                }
              }
              var fail = res => {
                wx.hideLoading();
              }
              var comp = () => { }
              app.request(url, params, success, fail, comp);
            }, 5000);

          } else if (res.info.err_code == "USERPAYING") { // 等待用户支付
            wx.navigateTo({
              url: '/pages/admin/waiting/waiting?code=' + res.info.code
            })
          } else {
            wx.showModal({
              title: '提示',
              content: '支付失败：' + res.info.err_code + '-' + res.info.err_code_des,
              showCancel: false
            })

            var url = host + '/yq/api/reverse';
            var params = {
              code: res.info.code
            }
            var success = function (res) {
              console.log(res);
              if (res.info.return_code == "SUCCESS" && res.info.result_code == "SUCCESS") {
                wx.showToast({
                  title: '撤单成功',
                  icon: 'none'
                })
              } else {
                wx.showToast({
                  title: '撤单失败：' + (res.info.err_code_des ? res.info.err_code_des : res.info.return_msg),
                  icon: 'none'
                })
              }
            }
            var fail = function (res) { }
            var comp = function () { }
            app.request(url, params, success, fail, comp);
          }
        }
        var fail = res => { }
        var complete = () => { }
        app.requestLoading(url, params, success, fail, complete);
      },
      fail: res => {
        console.log("扫码失败");
        console.log(res);
      }
    })
  },
  verifyCancel(e) {
    wx.scanCode({
      onlyFromCamera: true,
      scanType: ['qrCode'],
      success: res => {
        console.log("扫码成功");
        console.log(res);
        var code = res.result;
        var url = host + '/yq/api/use';
        var params = {
          code: code,
          suid: app.globalData.shopUser.id
        }
        var success = res => {
          console.log(res);
          var content = '';
          if (res.info.cardType == 1) { // 次卡
            content = '核销成功，使用次数限制 ' + res.info.useLimit + ' 次，已使用 ' + res.info.useCount + ' 次。';
          } else if (res.info.cardType == 2) { // 日卡
            content = '核销成功，剩余 ' + res.info.daysLeft + ' 天，已使用 ' + res.info.useCount + ' 次。';
          } else if (res.info.cardType == 3) { // 过期卡
            content = '核销成功，过期时间 ' + res.info.expireDay + '，已使用 ' + res.info.useCount + ' 次。';
          }
          wx.showModal({
            title: '提示',
            content: content,
            showCancel: false
          })
        }
        var fail = res => {
          if (res.status == 401) {
            self.logout();
          }
        }
        var comp = () => { }
        wx.showModal({
          title: '提示',
          content: '是否要核销？',
          success: obj => {
            if (obj.confirm) {
              app.requestLoading(url, params, success, fail, comp);
            }
          }
        })
      },
      fail: res => {
        console.log("扫码失败");
        console.log(res);
        wx.showModal({
          title: '提示',
          content: '扫码失败',
          showCancel: false
        })
      }
    })
  },
  logout(e) {
    wx.setStorageSync("shopUser", null);
    app.globalData.shopUser = null;
    wx.reLaunch({
      url: '/pages/admin/login/login'
    })
  },
  onUnload() {
    wx.setStorageSync("shpoUser", null);
    app.globalData.shopUser = null;
  }
})
